package com.cqkjxy.dao;

import com.cqkjxy.commons.dao.AbstractEntityDao;
import com.cqkjxy.entity.ScoringDetailEntity;
import com.cqkjxy.entity.StaffEntity;
import com.cqkjxy.entity.TechProjectEntity;
import com.cqkjxy.repositories.ScoringRepository;
import com.cqkjxy.repositories.StaffRepository;
import com.cqkjxy.repositories.TechProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Component
public class StaffDao extends AbstractEntityDao<StaffEntity, StaffRepository> {

    @Autowired
    private StaffRepository staffRepository;
    @Autowired
    private ScoringRepository scoringRepository;
    @Autowired
    private TechProjectRepository techProjectRepository;

    @Override
    protected StaffRepository getRepository() {
        return staffRepository;
    }

    @Override
    protected Sort getDefaultSorting() {
        return StaffEntity.DEFAULT_SORTING;
    }

    @Override
    protected void deleteRelations(Integer id) {
        List<ScoringDetailEntity> scores = scoringRepository.findByStaffEntity_PkId(id);
        scoringRepository.deleteAll(scores);
        Optional<StaffEntity> byId = staffRepository.findById(id);
        List<TechProjectEntity> mainStaffEntitiesPkId = techProjectRepository.findByMainStaffEntities_PkId(id);
        List<TechProjectEntity> otherStaffEntitiesPkId = techProjectRepository.findByOtherStaffEntities_PkId(id);
        for (TechProjectEntity techProjectEntity : mainStaffEntitiesPkId) {
            boolean remove = techProjectEntity.getMainStaffEntities().remove(byId.get());
        }
        for (TechProjectEntity techProjectEntity : otherStaffEntitiesPkId) {
            boolean remove = techProjectEntity.getOtherStaffEntities().remove(byId.get());
        }
        techProjectRepository.saveAll(mainStaffEntitiesPkId);
        techProjectRepository.saveAll(otherStaffEntitiesPkId);
    }

    /* *
     * @description delete：先删除实体间的关系，在删除实体
     * @author yang tao
     * @date 2021-12-24 17:03
     * @Param: id
     * @return void
     */
    public void deleteRelation(int id) {
        deleteRelations(id);
        staffRepository.deleteById(id);
    }
}
